<?php

namespace app\index\controller;

use think\Db;
use think\facade\Config;
use yibanApi\YBException;
use yibanApi\YBOpenApi;
use app\index\config\app;
use app\index\config\secret;

/**
 * 漂流瓶
 * @author qylh
 */
class Index
{
    /**
     * 入口文件/上线后使用易班接口/测试时直接定义了相关内容
     */
    public function index()
    {

        // 获取轻应用基本信息（在../config/app.php中）
        /*$AppID = Config::get('app.yiban_api.app_id');
        $AppSecret = Config::get('app.yiban_api.app_secret');
        $CallBack = Config::get('app.yiban_api.call_back');
        // 初始化
        $api = YBOpenApi::getInstance()->init($AppID, $AppSecret, $CallBack);
        // 获取APP授权
        $iapp = $api->getIApp();
        // 初始化 $info 变量
        $info = null;
        try {
            // 轻应用获取access_token，未授权则跳转至授权页面
            $info = $iapp->perform();
        } catch (YBException $ex) {
            return $ex;
        }
        // 轻应用获取的token
        $token = $info['visit_oauth']['access_token'];
        // 绑定token，
        // TODO 日后需要可以将$api(易班API接口SDK类)序列化后直接传递
        $api->bind($token);
        // 轻应用获取的userID
        $userID = $info['visit_user']['userid'];
        // 存入session
        session('userID', $userID);
        // 调用易班API接口
        $url = 'user/me';
        $result = $api->request($url, null, false, true);
        if ($result['status'] == 'success') {
            // 获取用户名
            $username = isset($result['info']['yb_username']) ? $result['info']['yb_username'] : 'nickname';
            // 获取用户头像
            $userhead = isset($result['info']['yb_userhead']) ? $result['info']['yb_userhead'] : WEB_DIR . 'static/img/head.jpg';

            // 存入session
            session('userName', $username);
            session('userHead', $userhead);
        } else {
            return 'error';
        }*/
        $my_ybid=1234;
        session('ybid', $my_ybid);
        return view('index', ['DIR' => WEB_DIR]);
    }
    /**
     * 判断本日是否已经发过普通漂流瓶
     * @return 1 or 0
     */
    public function judgeQualification()
    {
        $today = Db::table('db_info')->where('ybid', session('ybid'))->where('type', 1)->where('date', date('y-m-d'))->select();
        if (sizeof($today) == 0) {
            return 1;
        } else {
            return 0;
        }
    }
    /**
     * 扔瓶子(存数据库)
     */
    public function throwBottle()
    {
        $data = $_POST;
        //$bottle = array();
        $boddle['ybid'] = session('ybid');
        $boddle['type'] = $data['type'];
        $boddle['date'] = date('y-m-d');
        $boddle['praisenum'] = 0;
        if ($data['type'] == 1) {
            //漂流瓶
            $boddle['content'] = $data['contentType1'];
            $boddle['anonymous'] = $data['anonymous'];
            if($data['name']==null)
            {
                $data['name']='神秘人';
            }
            $boddle['name'] = $data['name'];
        } else {
            //隐身瓶
            //调用secret.php中的加密函数进行加密
            $encode_data = authcode($data['contentType2'], 'ENCODE');
            $boddle['content'] = $encode_data;
            //下面这两句还是得写，不然会跳500状态码
            $boddle['anonymous'] = 0;
            $boddle['name'] = $data['name'];
        }
        Db::table('db_info')->insert($boddle);
        return 1;
    }

    /**
     * 拿瓶子
     */
    public function getBottleInfo()
    {
        $my_ybid=session('ybid');
        //查找ybid不是发送者且属于漂流瓶的信息
        $info = Db::table('db_info')->where("ybid != $my_ybid and type = 1")->select();
        //以0~拿到的数据个数作为范围生成随机数得到下标索引
        $infoindex = rand(0,sizeof($info)-1);
        //将拿到的瓶子的id存到session里头
        session('bottleid',$info[$infoindex]['id']);
        //将信息提交给前端页面
        return json_encode($info[$infoindex]);
    }

    /**
     * 点赞
     */
    public function praise()
    {
        $ybid=session('ybid');
        $bottleid=session('bottleid');
        $nowdate=date('y-m-d');//获取当前点赞时间
        $record=Db::table('db_record')->where("ybid = $ybid and bottleid = $bottleid")->select();
        if($record==null)//若没有点赞记录,直接插入一条记录，并更新点赞数
        {
            $data['ybid']=$ybid;
            $data['bottleid']=$bottleid;
            $data['date']=$nowdate;
            Db::table('db_record')->insert($data);
            Db::table('db_info')->where("id = $bottleid")->setInc('praisenum');
            return 1;
        }
        $distance=strtotime($record[0]['date'])-strtotime($nowdate);//切记那个record拿出来是个二维数组!!!
        // $test=ceil($distance/(3600*24));
        // return $test;
        if(ceil($distance/(3600*24))==0)//看看差距点赞时间差有没有至少一天
        {
            //若时间在同一天
            return 0;
        }
        else
        {
            //若时间不在同一天
            //将info表中的点赞数更新
            Db::table('db_info')->where("id = $bottleid")->setInc('praisenum');
            //将record表中的点赞时间更新
            Db::table('db_record')->where("ybid = $ybid and bottleid = $bottleid")->update(['date'=>$nowdate]);
            return 1;
        }
    }

    public function getRank()
    {
        //从info表中按点赞数目从大到小拿出数据
        $data=Db::table('db_info')->where('id!=0')->order('praisenum','desc')->select();//desc是降序，asc是升序
        return json_encode($data); 
    }
}
